<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useGetAgreementPage, useStopAgreement } from '@fl/api/supplier'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import { AGREEMENT_STATE, AGREEMENT_STATE_MAP, AGREEMENT_TYPE } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/supplier-pages/order-management/protocol-management',
})

const { createConfirmModal } = useMessage()
const router = useRouter()

const initialState = {
    agreementCode: '',
    agreementName: '',
    agreementState: '',
    agreementType: '',
    partyA: '',
}
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getAgreementPageParams = computed(() => ({
    ...searchConditions.value,
    page: tablePage.currentPage,
    size: tablePage.pageSize,
}))

const { data: agreementPageData, isLoading: isGetAgreementPageLoading, total: agreementTotal } = useGetAgreementPage(getAgreementPageParams)
const { isPending: _isStopAgreementPending, mutate: stopAgreement } = useStopAgreement()

// #region Form
const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '状态',
        options: AGREEMENT_STATE,
        prop: 'agreementState',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '协议类型',
        options: AGREEMENT_TYPE,
        prop: 'agreementType',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '协议编号',
        prop: 'agreementCode',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '协议名称',
        prop: 'agreementName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '甲方',
        prop: 'partyA',
        valueType: 'copy',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const isTableLoading = computed(() => isGetAgreementPageLoading.value)

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'agreementCode', title: '协议编号' },
        { field: 'agreementName', slots: { default: 'agreement_name' }, title: '协议名称' },
        { field: 'agreementType', formatter: formatAgreementType, title: '协议类型' },
        { field: 'categoryName', title: '协议类目' },
        { field: 'partyA', title: '甲方' },
        { field: 'endDate', title: '协议到期日' },
        { field: 'agreementState', formatter: formatAgreementState, title: '协议状态' },
        { slots: { default: 'operation' }, title: '操作', width: 200 },
    ],
})

function formatAgreementType({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: AGREEMENT_TYPE })
}

function formatAgreementState({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: AGREEMENT_STATE })
}

watchEffect(() => {
    tablePage.total = agreementTotal.value
})
// #endregion

// #region UI Listener
function onCheckDetailBtnClick(row: any) {
    router.push(`/supplier-pages/order-management/protocol-detail/${row.id}`)
}

function onStopBtnClick(row: any) {
    createConfirmModal({
        content: '确定要停用该协议吗？',
        onSuccess: () => {
            stopAgreement(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onAddBtnClick() {
    router.push({ path: '/supplier-pages/order-management/add-protocol' })
}

function onAgreementNameClick(row: any) {
    onCheckDetailBtnClick(row)
}
// #endregion
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="agreementPageData"
        >
            <template #operation="{ row }">
                <el-button text
                           type="primary"
                           class="!p-4"
                           @click="onCheckDetailBtnClick(row)"
                >
                    查看
                </el-button>

                <el-button v-if="row.agreementState === AGREEMENT_STATE_MAP.VALIDATED"
                           text
                           type="danger"
                           class="!p-4"
                           @click="onStopBtnClick(row)"
                >
                    停用
                </el-button>
            </template>

            <template #toolbar_buttons>
                <el-space class="mb-12">
                    <el-button type="primary"
                               @click="onAddBtnClick"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新增协议
                    </el-button>
                </el-space>
            </template>

            <template #agreement_name="{ row }">
                <span class="text-#409EFF truncate cursor-pointer"
                      @click="onAgreementNameClick(row)"
                >
                    {{ row.agreementName }}
                </span>
            </template>
        </SearchTable>
    </el-card>
</template>
